package com.minxi.jsp.controller;

import com.minxi.jsp.javabean.Userinfo;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.sql.PreparedStatement;
import java.sql.Connection;
@WebServlet(name = "ListServlet",urlPatterns = "/list")

public class ListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        List<Userinfo> list = new ArrayList<>();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shanghai";
            String user = "root";
            String pwd = "123456";
            conn = DriverManager.getConnection(url, user, pwd);
            String sql = "select id,user_name,user_pwd,user_phone,user_sex from user_info;";
            pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                Userinfo userinfo = new Userinfo();
                userinfo.setId(rs.getLong("id"));
                userinfo.setUserName(rs.getString("user_name"));
                userinfo.setUserPwd(rs.getString("user_pwd"));
                userinfo.setUserPhone(rs.getString("user_phone"));
                userinfo.setUserSex(rs.getInt("user_sex"));
                list.add(userinfo);
            }
            HttpSession session = req.getSession();
            session.setAttribute("userList", list);
            resp.sendRedirect("jsp/home.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
              pstmt.close();
              conn.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            {
            }
        }
    }
}

